package com.cby.code.net2;

import com.cby.code.net.Request;
import com.cby.code.net.Response;
import com.cby.code.net.engine.BaseEngine;
import com.cby.code.net.engine.DefaultEngine;
import com.cby.code.net.listener.ResponseListener;
import com.cby.code.net.task.BaseTask;
import com.cby.code.net.task.HttpUrlDownloadFileTask;
import com.cby.code.net.task.HttpUrlUploadFileTask;
import com.cby.code.net2.action.BaseAction;
import com.cby.code.net2.action.RealAction;


/**
 * @description: OliveNetCallImpl
 * @author: ChenBaoYang
 * @createDate: 2022/3/8 11:14 上午
 */
final class OliveNetCallImpl implements NetCall{

    private String baseUrl;

    public OliveNetCallImpl(String baseUrl) {
        this.baseUrl = baseUrl;
    }

    @Override
    public Response apply(NetCallRequest callRequest) {
        BaseAction action = new RealAction();
        return action.doAction(cloneRequest(callRequest.getRequest()));
    }

    @Override
    public Response downloadFile(NetCallRequest callRequest) {
        BaseTask fileTask = new HttpUrlDownloadFileTask();
        BaseAction action = new RealAction(fileTask);
        return action.doAction(cloneRequest(callRequest.getRequest()));
    }

    @Override
    public void downloadFile(NetCallRequest callRequest, ResponseListener listener) {
        BaseTask fileTask = new HttpUrlDownloadFileTask();
        BaseEngine engine = new DefaultEngine(fileTask, cloneRequest(callRequest.getRequest()));
        engine.setListener(listener);
        engine.doWork();
    }

    @Override
    public Response uploadFile(NetCallRequest callRequest) {
        BaseTask fileTask = new HttpUrlUploadFileTask();
        BaseAction action = new RealAction(fileTask);
        return action.doAction(cloneRequest(callRequest.getRequest()));
    }

    @Override
    public void uploadFile(NetCallRequest callRequest, ResponseListener listener) {
        BaseTask fileTask = new HttpUrlUploadFileTask();
        BaseEngine engine = new DefaultEngine(fileTask, cloneRequest(callRequest.getRequest()));
        engine.setListener(listener);
        engine.doWork();
    }

    @Override
    public void apply(NetCallRequest callRequest, ResponseListener listener) {
        BaseEngine engine = new DefaultEngine(cloneRequest(callRequest.getRequest()));
        engine.setListener(listener);
        engine.doWork();
    }

    private Request cloneRequest(Request oldRequest) {
        return new Request.Builder()
                .setUrl(baseUrl)
                .setPathSegment(oldRequest.getPathSegment())
                .setFilePath(oldRequest.getFilePath())
                .setMethod(oldRequest.getMethod())
                .setRequestParam(oldRequest.getParam())
                .setRetryPolicy(oldRequest.getRetryPolicy())
                .build();

    }
}
